<template>
  <div class="app-container">
    <Sidebar
        :conversations="conversations"
        @select="handleSelectConversation"
        @new-chat="handleNewChat"
    />

    <div class="chat-container">
      <div class="chat-header">
        <h2>{{ conversationName || '新对话' }}</h2>
      </div>

      <div class="chat-messages" ref="messagesContainer">
        <!-- 欢迎消息 -->
        <ChatMessage
            :message="{ answer: welcomeMessage }"
            type="answer"
        />

        <!-- 对话消息 -->
        <template v-for="(msg, index) in messages" :key="index">
          <!-- 用户问题 -->
          <ChatMessage
              v-if="msg.question"
              :message="{ question: msg.question }"
              type="question"
          />
          <!-- AI回答 -->
          <ChatMessage
              v-if="msg.answer"
              :message="{ answer: msg.answer }"
              type="answer"
          />
        </template>
      </div>

      <div class="chat-input-container">
        <ChatInput @send="handleSendQuestion"/>
      </div>
    </div>
  </div>
</template>

<script>
import {ref, onMounted, watch, nextTick} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import Sidebar from '../AI/Sidebar.vue'
import ChatInput from '../AI/ChatInput.vue'
import ChatMessage from '../AI/ChatMessage.vue'
import useApi from '../AI/useApi'

export default {
  components: {Sidebar, ChatInput, ChatMessage},
  setup() {
    const route = useRoute()
    const router = useRouter()
    const api = useApi()
    const messages = ref([])
    const conversations = ref([])
    const conversationName = ref('')
    const messagesContainer = ref(null)
    const isLoading = ref(false)
    const conversationId = ref('')
    const welcomeMessage = '我是问答系统小琳，我可以帮你解决IT行业、医疗行业和人事行业的问题，请把你的问题告诉我'

    const validateConversationId = () => {
      if (!conversationId.value || conversationId.value === 'undefined') {
        console.error('无效的会话ID:', conversationId.value)
        return false
      }
      return true
    }

    const fetchConversations = async () => {
      try {
        conversations.value = await api.getAllConversations(localStorage.getItem('userid'))
      } catch (error) {
        console.error('加载会话列表失败:', error)
      }
    }

    const loadConversation = async () => {
      conversationId.value = route.params.id
      if (!validateConversationId()) return

      try {
        isLoading.value = true
        const details = await api.getConversationDetails(conversationId.value)

        // 重置消息，只保留从API获取的对话记录
        messages.value = details.map(item => ({
          question: item.question || '',
          answer: item.answer || '',
          timestamp: item.created_at
        }))

        if (details.length > 0) {
          conversationName.value = details[0].question
        }
      } catch (error) {
        console.error('加载会话失败:', error)
      } finally {
        isLoading.value = false
        scrollToBottom()
      }
    }

    const scrollToBottom = () => {
      nextTick(() => {
        if (messagesContainer.value) {
          messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
        }
      })
    }

    const handleSendQuestion = async (question) => {
      if (!question.trim() || !validateConversationId()) return

      try {
        isLoading.value = true

        // 添加用户问题
        messages.value.push({
          question: question,
          answer: '', // 先留空，等待AI回答
          timestamp: new Date().toISOString()
        })

        scrollToBottom()

        // 获取AI回答
        const response = await api.getAnswer(conversationId.value, question)

        // 更新最后一条消息的AI回答
        messages.value[messages.value.length - 1].answer = response.answer

        // 如果是第一个问题，更新会话名称
        if (messages.value.length === 1) {
          await api.updateConversationName(conversationId.value, question)
          conversationName.value = question
          await fetchConversations()
        }
      } catch (error) {
        console.error('发送问题失败:', error)
        // 出错时也更新最后一条消息的AI回答
        messages.value[messages.value.length - 1].answer = '获取回答时出错，请稍后再试'
      } finally {
        isLoading.value = false
        scrollToBottom()
      }
    }

    const handleSelectConversation = (id) => {
      router.push({name: 'chat', params: {id}})
    }

    const handleNewChat = () => {
      router.push({name: 'home'})
    }

    onMounted(() => {
      fetchConversations()
      loadConversation()
    })
    watch(() => route.params.id, loadConversation)

    return {
      messages,
      conversations,
      conversationName,
      messagesContainer,
      isLoading,
      welcomeMessage,
      handleSendQuestion,
      handleSelectConversation,
      handleNewChat
    }
  }
}
</script>

<style scoped>
.app-container {
  display: flex;
  height: 100vh;
  background-color: #f5f5f5;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #fff;
}

.chat-header {
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #e8e8e8;
  background-color: #fafafa;
}

.chat-header h2 {
  margin: 0;
  font-size: 1.25rem;
  color: #333;
  font-weight: 500;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 1.5rem;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  background-color: #f9f9f9;
}

.chat-input-container {
  padding: 1rem;
  border-top: 1px solid #e8e8e8;
  background-color: #fff;
}
</style>